import * as request from "../services/CommonHttpService";
import {baseEffects, baseReducers} from "./baseModel";
import { routerRedux } from 'dva/router';

export default {

  namespace: 'global',

  state: {
    locaPath: undefined,
    name: "管理员",
  },

  subscriptions: {
    setup({dispatch, history}) {  // eslint-disable-line

      history.listen(location => {
        // location.pathname
        const len = location.pathname.length;
        const payload = location.pathname.slice(1, len).split('/');
        dispatch({
          type: 'ruteChange',
          payload,
        });
      });
    },
  },

  effects: {

    ...baseEffects,

    * fetch({payload}, {call, put}) {  // eslint-disable-line
      yield put({type: 'save'});
    },

    * getName({payload}, {call, put}) {

      const {errorMsg, notice, server} = payload;
      try {
        let result = yield call(request.commonGet, '/admin/name', {}, {}, server);
        yield put({
          type: 'initState',
          payload: {
            name: result
          }
        });
      } catch (error) {
        console.error("getName", error);
        !!notice && notice("error", !!errorMsg ? errorMsg : error);
        yield put(routerRedux.push('/sign/login'));
      }
    }
  },

  reducers: {

    ...baseReducers,

    save(state, action) {
      return {...state, ...action.payload};
    },

    ruteChange(state, action) {
      return {...state, locaPath: action.payload};
    },
  },

};
